// -----------------------------------------------------------------------
//  <copyright file="PageQuerySpecification.cs" company="LiuliuSoft">
//      Copyright (c) 2022-2024 DaprPlus. All rights reserved.
//  </copyright>
//  <site>https://dapr.plus</site>
//  <last-editor>郭明锋</last-editor>
//  <last-date>2024/12/6 16:13:34</last-date>
// -----------------------------------------------------------------------

using DaprPlus.Domain.Entity;
using DaprPlus.Filters;

using OSharp.Filter;


namespace DaprPlus.Specifications;

public sealed class PageQuerySpecification<T> : SpecificationBase<T> where T : IEntity
{
    public PageQuerySpecification(PageCondition pageCondition, FilterGroup? filterGroup) : base(GetExpression(filterGroup))
    {
        if (pageCondition is { PageIndex: > 0, PageSize: > 0 })
        {
            var take = pageCondition.PageSize;
            var skip = (pageCondition.PageIndex - 1) * pageCondition.PageSize;
            ApplyPaging(skip, take);
        }

        if (pageCondition.SortConditions?.Length > 0)
        {
            foreach (var sortCondition in pageCondition.SortConditions)
            {
                AddOrderBy(sortCondition.SortField, sortCondition.ListSortDirection == ListSortDirection.Descending);
            }
        }
    }

    private static Expression<Func<T, bool>> GetExpression(FilterGroup? filterGroup)
    {
        if (filterGroup == null)
        {
            return m => true;
        }
        return filterGroup.ToExpression<T>();
    }

    public PageQuerySpecification<T> AddIncludeEx(Expression<Func<T, object>> exp)
    {
        AddInclude(exp);

        return this;
    }
}
